﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace DNA.Mvc.jQuery
{
    public class Pager : ViewComponent { }

    public class PagerBuilder : jQueryComponentBuilder<PagerOptions, Pager, PagerBuilder>
    {
        private string _index = "index";
        private string _sizeField = "size";
        private string _recordsField = "totalRecords";
        private string _remoteUrl = "";

        protected override string jQueryPluginName
        {
            get { return "pager"; }
        }

        public PagerBuilder MapRouteValues(string indexField, string sizeField, string totalRecords)
        {
            if (!string.IsNullOrEmpty(indexField))
                _index = indexField;

            if (!string.IsNullOrEmpty(sizeField))
                _sizeField = sizeField;

            if (!string.IsNullOrEmpty(totalRecords))
                _recordsField = totalRecords;

            return this;
        }

        public PagerBuilder Load(string url)
        {
            _remoteUrl = url;
            return this;
        }

        public PagerBuilder(Pager component, ViewContext viewContext, IViewDataContainer viewContainer) : base(component, viewContext, viewContainer) { }

        public override void Render()
        {
            if (!string.IsNullOrEmpty(_remoteUrl))
            {
                var values = this.ViewContext.RequestContext.HttpContext.Request.QueryString; 

                Options(opts =>
                {
                    opts.PageIndex = values.AllKeys.Contains(_index) ? int.Parse(values[_index]) : 1; 
                    opts.PageSize = values.AllKeys.Contains(_sizeField) ?int.Parse(values[_sizeField]) : 20; 
                    opts.TotalRecords = this.ViewContext.ViewData[_recordsField] != null ? (int)this.ViewContext.ViewData[_recordsField] : 0;
                    opts.OnPageIndexChanged = "location=\"" + _remoteUrl + (_remoteUrl.IndexOf("?") > -1 ? "&" : "?") +
                        "index=\"+ui.pageIndex+\"&size=\"+ui.pageSize;";
                });
            }

            base.Render();
        }
    }
}
